package com.atguigu.gulimall.member.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.utils.HttpClientUtil;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.gulimall.member.dao.MemberLevelDao;
import com.atguigu.gulimall.member.entity.MemberLevelEntity;
import com.atguigu.gulimall.member.exception.LoginAcctException;
import com.atguigu.gulimall.member.exception.LoginPasswordException;
import com.atguigu.gulimall.member.exception.PhoneExistException;
import com.atguigu.gulimall.member.exception.UserNameExistException;
import com.atguigu.gulimall.member.vo.GiteeUser;
import com.atguigu.gulimall.member.vo.MemberLoginVo;
import com.atguigu.gulimall.member.vo.MemberRegistVo;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.member.dao.MemberDao;
import com.atguigu.gulimall.member.entity.MemberEntity;
import com.atguigu.gulimall.member.service.MemberService;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    private MemberLevelDao memberLevelDao;
    private static final String salt="cLo8QmTG";
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 社交登录-gitee登录
     * @param giteeUser
     * @return
     */
    @Override
    public MemberEntity oauth2Login(GiteeUser giteeUser) throws Exception {
        //登录和注册合并逻辑
        //查询当前社交用户的信息
        Map<String,String> query=new HashMap<>();
        query.put("access_token",giteeUser.getAccess_token());
        String uid=null;
        try{
            //HttpResponse response = HttpUtils.doGet("https://gitee.com", "/api/v5/user", "get", new HashMap<String, String>(), query);
            String response = HttpClientUtil.doGet("https://gitee.com/api/v5/user", query);
            //if(response.getStatusLine().getStatusCode()==200){
            if(!StringUtils.isEmpty(response)){
                //String json = EntityUtils.toString(response.getEntity());
                JSONObject jsonObject = JSONObject.parseObject(response);
                uid = jsonObject.getString("id");
            }
        }catch (Exception e){}

        //1 判断当前社交用户是否已注册过
        MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if(memberEntity != null){
            MemberEntity update=new MemberEntity();
            update.setId(memberEntity.getId());
            update.setAccessToken(giteeUser.getAccess_token());
            update.setExpiresIn(giteeUser.getExpires_in());
            this.baseMapper.updateById(update);
            memberEntity.setAccessToken(giteeUser.getAccess_token());
            memberEntity.setExpiresIn(giteeUser.getExpires_in());
            return memberEntity;
        }else {
            MemberEntity regist= new MemberEntity();
            //2注册
            try {
                String response = HttpClientUtil.doGet("https://gitee.com/api/v5/user", query);
                if(!StringUtils.isEmpty(response)){
                    JSONObject jsonObject = JSONObject.parseObject(response);
                    String name = jsonObject.getString("name");
                    String socialUid = jsonObject.getString("id");
                    regist.setNickname(name);
                    regist.setSocialUid(socialUid);
                }
            }catch (Exception e){}
            regist.setAccessToken(giteeUser.getAccess_token());
            regist.setExpiresIn(giteeUser.getExpires_in());
            if(regist.getSocialUid()!=null){
                this.baseMapper.insert(regist);
                return regist;
            }else {
                return null;
            }

        }
    }

    /**
     * 登录
     * @param vo
     */
    @Override
    public MemberEntity login(MemberLoginVo vo) throws RuntimeException {

        QueryWrapper<MemberEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",vo.getLoginacct()).or().eq("mobile",vo.getLoginacct()).or().eq("email",vo.getLoginacct());
        MemberEntity memberEntity = this.baseMapper.selectOne(queryWrapper);
        if(memberEntity == null){
            throw new LoginAcctException();
        }else {
            BCryptPasswordEncoder passwordEncoder=new BCryptPasswordEncoder();
            if(!passwordEncoder.matches(vo.getPassword(),memberEntity.getPassword())){
                throw new LoginPasswordException();
            }else{
                return memberEntity;
            }
        }

    }

    /**
     * 注册
     * @param vo
     */
    @Override
    public void regist(MemberRegistVo vo) {
        MemberEntity memberEntity = new MemberEntity();
        MemberLevelEntity memberLevelEntity = memberLevelDao.getDefaultLevel();
        memberEntity.setLevelId(memberLevelEntity.getId());

        //检查用户名和手机号是否唯一.异常机制可以让controller层捕获异常
        checkPhoneUnique(vo.getPhone());
        checkUserNameUnique(vo.getUserName());
        memberEntity.setMobile(vo.getPhone());
        memberEntity.setUsername(vo.getUserName());
        //默认昵称为用户名
        memberEntity.setNickname(vo.getUserName());
        //MD5加密,盐值加密:随机值 加盐:$1$+8位字符串,数据库存放盐值

        /*
        String password= vo.getPassword();
        String md5password=salt.charAt(0)+password+salt.charAt(5);
        password= DigestUtils.md5DigestAsHex(md5password.getBytes());
        System.out.println(password);
        memberEntity.setPassword(password);
        */
        //BCryptPasswordEncoder密码加密器自动存放盐值
        BCryptPasswordEncoder passwordEncoder=new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(vo.getPassword());
        memberEntity.setPassword(encode);
        this.baseMapper.insert(memberEntity);
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException{
        Integer mobile = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if(mobile>0){
            throw new PhoneExistException();
        }

    }

    @Override
    public void checkUserNameUnique(String userName) throws UserNameExistException {
        Integer username = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", userName));
        if(username>0){
            throw new UserNameExistException();
        }
    }


    @Override
    public void updateMemberMoney(String pay,Long id) {
        MemberEntity memberEntity = new MemberEntity();
        memberEntity.setId(id);
        memberEntity.setMemberMoney(new BigDecimal(pay));
        baseMapper.updateById(memberEntity);
    }
}
